/*
 *  Copyright 2019-2025 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousAccess;
import me.zhengjie.config.properties.RsaProperties;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.dto.UserPassVo;
import me.zhengjie.modules.system.domain.dto.UserQueryCriteria;
import me.zhengjie.utils.*;
import me.zhengjie.utils.enums.CodeEnum;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-11-23
 */
@Api(tags = "系统：用户管理")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final PasswordEncoder passwordEncoder;
    private final UserService userService;
    private final DataService dataService;
    private final DeptService deptService;
    private final RoleService roleService;
    private final VerifyService verificationCodeService;
    private final PokerUserServerInfoService userServerInfoService;
    private final PokerServerService serverService;
    private final LevelInfoConfigService levelInfoConfigService;

    @ApiOperation("导出用户数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('user:list')")
    public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
        userService.download(userService.queryAll(criteria), response);
    }

    @GetMapping(value = "/getUserList")
    public ResponseEntity<List<User>> getUserList()   {
        return new ResponseEntity<>(userService.list(),HttpStatus.OK);
    }

    @ApiOperation("查询用户")
    @GetMapping
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<PageResult<User>> queryUser(UserQueryCriteria criteria){
        Page<Object> page = new Page<>(criteria.getPage(), criteria.getSize());
        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            criteria.getDeptIds().add(criteria.getDeptId());
            // 先查找是否存在子节点
            List<Dept> data = deptService.findByPid(criteria.getDeptId());
            // 然后把子节点的ID都加入到集合中
            criteria.getDeptIds().addAll(deptService.getDeptChildren(data));
        }
        // 数据权限
        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));
        // criteria.getDeptIds() 不为空并且数据权限不为空则取交集
        if (!CollectionUtils.isEmpty(criteria.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
            // 取交集
            criteria.getDeptIds().retainAll(dataScopes);
            if(!CollectionUtil.isEmpty(criteria.getDeptIds())){
                return new ResponseEntity<>(userService.queryAll(criteria,page),HttpStatus.OK);
            }
        } else {
            // 否则取并集
            criteria.getDeptIds().addAll(dataScopes);
            return new ResponseEntity<>(userService.queryAll(criteria,page),HttpStatus.OK);
        }
        return new ResponseEntity<>(PageUtil.noData(),HttpStatus.OK);
    }

    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping
    @PreAuthorize("@el.check('user:add')")
    public ResponseEntity<Object> createUser( @RequestBody User resources){
        checkLevel(resources);
        resources.setSteamId("steam_"+resources.getSteamId());
        // 默认密码 123456
        resources.setPassword(passwordEncoder.encode("123456"));
        List<User> userList = userService.list();
        for (User user : userList) {
            if (ObjectUtil.isNotEmpty(user.getSteamId())){
                if (user.getSteamId().equals(resources.getSteamId())){
                    throw new BadRequestException("steamId重复，请重试");

                }
            }
        }
        userService.create(resources);

        //每个服务器资源创建初始记录
        List<PokerServer> serverList = serverService.list();
        ArrayList<PokerUserServerInfo> pokerUserServerInfos = new ArrayList<>();
        for (PokerServer pokerServer : serverList) {
            PokerUserServerInfo userServerInfo = new PokerUserServerInfo();
            userServerInfo.setUserId(resources.getId());
            userServerInfo.setServerId(pokerServer.getId());
            userServerInfo.setJettonNum(0);
            pokerUserServerInfos.add(userServerInfo);
        }
        userServerInfoService.saveBatch(pokerUserServerInfos);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PostMapping("/botUserAdd")
    @AnonymousAccess
    public ResponseEntity<Object> botUserAdd( @RequestBody User user){
        List<User> userList = userService.list();
        user.setSteamId("steam_"+user.getSteamId());
        for (User userEx : userList) {
            if (ObjectUtil.isNotEmpty(userEx.getSteamId())){
                if (userEx.getSteamId().equals(user.getSteamId())){
                    return new ResponseEntity<>("steamId重复，请重试",HttpStatus.ACCEPTED);

                }
            }
            if (ObjectUtil.isNotEmpty(userEx.getUsername())){
                if (userEx.getUsername().equals(user.getUsername())){
                    return new ResponseEntity<>("账户名重复，请重试",HttpStatus.ACCEPTED);

                }
            }
            if (ObjectUtil.isNotEmpty(userEx.getEmail())){
                if (userEx.getEmail().equals(user.getEmail())){
                    return new ResponseEntity<>("邮箱重复，请重试",HttpStatus.ACCEPTED);

                }
            }
            if (ObjectUtil.isNotEmpty(userEx.getPhone())){
                if (userEx.getPhone().equals(user.getPhone())){
                    return new ResponseEntity<>("手机号重复，请重试",HttpStatus.ACCEPTED);

                }
            }

        }
        Dept dept = new Dept();
        dept.setId(7L);
        user.setDept(dept);
        user.setEnabled(true);
        user.setGender("男");
        user.setJettonNum(0);
        Job job = new Job();
        job.setId(12L);
        Set<Job> jobs = new LinkedHashSet<>();
        jobs.add(job);
        user.setJobs(jobs);
        Role role = new Role();
        role.setId(2L);
        Set<Role> roles = new LinkedHashSet<>();
        roles.add(role);
        user.setRoles(roles);
        if (ObjectUtil.isNotEmpty(user.getPassword())){
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }else{
            user.setPassword(passwordEncoder.encode("123456"));
        }
        user.setCreateBy("admin");
        user.setUpdateBy("admin");
        user.setIsAdmin(false);
        userService.create(user);

        //每个服务器资源创建初始记录
        List<PokerServer> serverList = serverService.list();
        ArrayList<PokerUserServerInfo> pokerUserServerInfos = new ArrayList<>();
        for (PokerServer pokerServer : serverList) {
            PokerUserServerInfo userServerInfo = new PokerUserServerInfo();
            userServerInfo.setUserId(user.getId());
            userServerInfo.setServerId(pokerServer.getId());
            userServerInfo.setJettonNum(0);
            pokerUserServerInfos.add(userServerInfo);
        }
        userServerInfoService.saveBatch(pokerUserServerInfos);
        return new ResponseEntity<>("注册完成",HttpStatus.OK);
    }

    @PostMapping("/userInput/upload")
    @AnonymousAccess
    public ResponseEntity<Object> userExcelInput(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BadRequestException("文件为空");
        }

        // 读取文件内容
        String content = IoUtil.readUtf8(file.getInputStream());
        // 解析JSON内容
        JSONObject entries = JSONUtil.parseObj(content);
        JSONArray records = entries.getJSONArray("RECORDS");
        List<User> userList = userService.list();
        Integer sameCount = 0;
        Integer userCount = records.size();
        List<PokerServer> serverList = serverService.list();

        for (Object record : records) {
            JSONObject json = (JSONObject)record;
            for (User user : userList) {
                if (user.getSteamId().equals(json.getStr("steamId"))){
                    sameCount++;
                }
            }
            User user = new User();
            user.setSteamId(json.getStr("steamId"));
            Dept dept = new Dept();
            dept.setId(7L);
            user.setDept(dept);
            user.setEnabled(true);
            user.setGender("男");
            user.setJettonNum(0);
            Job job = new Job();
            job.setId(12L);
            Set<Job> jobs = new LinkedHashSet<>();
            jobs.add(job);
            user.setJobs(jobs);
            Role role = new Role();
            role.setId(2L);
            Set<Role> roles = new LinkedHashSet<>();
            roles.add(role);
            user.setRoles(roles);
            user.setPassword(passwordEncoder.encode("123456"));
            user.setUsername("User"+ RandomUtil.randomInt(1,20000));
            user.setNickName(json.getStr("qq"));

            userService.create(user);
            ArrayList<PokerUserServerInfo> pokerUserServerInfos = new ArrayList<>();
            for (PokerServer pokerServer : serverList) {
                PokerUserServerInfo userServerInfo = new PokerUserServerInfo();
                userServerInfo.setUserId(user.getId());
                userServerInfo.setServerId(pokerServer.getId());
                userServerInfo.setJettonNum(0);
                pokerUserServerInfos.add(userServerInfo);
            }
            userServerInfoService.saveBatch(pokerUserServerInfos);
        }


        String text  = String.format("成功导入了%d名用户，失败%d",userCount,sameCount);
        // 返回解析结果
        return new ResponseEntity<>(text,HttpStatus.CREATED);
    }


    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping
    @PreAuthorize("@el.check('user:edit')")
    public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody User resources) throws Exception {
        checkLevel(resources);
        userService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("修改用户：个人中心")
    @ApiOperation("修改用户：个人中心")
    @PutMapping(value = "center")
    public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources){
        if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){
            throw new BadRequestException("不能修改他人资料");
        }
        userService.updateCenter(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("修改用户：个人中心")
    @ApiOperation("修改用户：个人中心")
    @GetMapping(value = "getUser")
    public ResponseEntity<Object> getUser(String serverId){

        Long currentUserId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(currentUserId);

        LambdaQueryWrapper<PokerUserServerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerUserServerInfo::getUserId,currentUserId).eq(PokerUserServerInfo::getServerId,serverId);
        PokerUserServerInfo one = userServerInfoService.getOne(wrapper);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("user",user);
        map.put("num",one.getJettonNum());
        String levelName = userService.getLevelName(user.getEmpiricalVal());
        map.put("levelName",levelName);
        List<LevelInfoConfig> list = levelInfoConfigService.list();
        for (LevelInfoConfig levelInfoConfig : list) {
            if (user.getEmpiricalVal()>=levelInfoConfig.getLevalStartVal()&&user.getEmpiricalVal()<levelInfoConfig.getLevalEndVal()){
                map.put("levelInfo",levelInfoConfig);
            }
        }
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

    @GetMapping(value = "userById")
    public ResponseEntity<Object> userById(){
        Long currentUserId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(currentUserId);
        return new ResponseEntity<>(user,HttpStatus.OK);
    }

    @Log("删除用户")
    @ApiOperation("删除用户")
    @DeleteMapping
    @PreAuthorize("@el.check('user:del')")
    public ResponseEntity<Object> deleteUser( @RequestBody Set<Long> ids){
        for (Long id : ids) {
            Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(Role::getLevel).collect(Collectors.toList()));
            Integer optLevel =  Collections.min(roleService.findByUsersId(id).stream().map(Role::getLevel).collect(Collectors.toList()));
            if (currentLevel > optLevel) {
                throw new BadRequestException("角色权限不足，不能删除：" + userService.findById(id).getUsername());
            }
        }
        userService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());
        User user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(oldPass, user.getPassword())){
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if(passwordEncoder.matches(newPass, user.getPassword())){
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("重置密码")
    @PutMapping(value = "/resetPwd")
    public ResponseEntity<Object> resetPwd(@RequestBody Set<Long> ids) {
        String pwd = passwordEncoder.encode("123456");
        userService.resetPwd(ids, pwd);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改头像")
    @PostMapping(value = "/updateAvatar")
    public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){
        return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
    }

    @Log("修改邮箱")
    @ApiOperation("修改邮箱")
    @PostMapping(value = "/updateEmail/{code}")
    public ResponseEntity<Object> updateUserEmail(@PathVariable String code, @RequestBody User resources) throws Exception {
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,resources.getPassword());
        User user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(password, user.getPassword())){
            throw new BadRequestException("密码错误");
        }
        verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + resources.getEmail(), code);
        userService.updateEmail(user.getUsername(),resources.getEmail());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 如果当前用户的角色级别低于创建用户的角色级别，则抛出权限不足的错误
     * @param resources /
     */
    private void checkLevel(User resources) {
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(Role::getLevel).collect(Collectors.toList()));
        Integer optLevel = roleService.findByRoles(resources.getRoles());
        if (currentLevel > optLevel) {
            throw new BadRequestException("角色权限不足");
        }
    }
}
